<template>
  <div class="order-container">
    <h1>订单管理</h1>
    
    <el-tabs v-model="activeTab" @tab-click="handleTabChange">
      <el-tab-pane label="待接单" name="available"></el-tab-pane>
      <el-tab-pane label="配送中" name="inProgress"></el-tab-pane>
      <el-tab-pane label="已完成" name="completed"></el-tab-pane>
    </el-tabs>
    
    <div v-loading="loading">
      <el-table :data="orders" style="width: 100%">
        <el-table-column prop="orderNumber" label="订单号" width="150"></el-table-column>
        <el-table-column label="商家" width="150">
          <template slot-scope="scope">
            {{ scope.row.merchantName || scope.row.merchant_name || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="顾客" width="120">
          <template slot-scope="scope">
            {{ scope.row.userName || scope.row.user_name || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="address" label="配送地址"></el-table-column>
        <el-table-column prop="phone" label="联系电话" width="130"></el-table-column>
        <el-table-column label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="金额" width="100">
          <template slot-scope="scope">
            {{ scope.row.payAmount ? '¥' + scope.row.payAmount : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="下单时间" width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createdTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="viewOrder(scope.row)">查看</el-button>
            <el-button size="mini" type="success" v-if="activeTab === 'available'" @click="handleTakeOrder(scope.row)">接单</el-button>
            <el-button size="mini" type="success" v-if="activeTab === 'inProgress'" @click="handleCompleteOrder(scope.row)">完成</el-button>
            <el-button size="mini" type="warning" v-if="activeTab === 'inProgress'" @click="navigateToOrder(scope.row)">导航</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.page"
          :page-sizes="[10, 20, 50]"
          :page-size="pagination.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
        </el-pagination>
      </div>
      
      <!-- 订单为空时显示 -->
      <div class="empty-data" v-if="orders.length === 0 && !loading">
        <el-empty description="暂无订单数据"></el-empty>
      </div>
    </div>
    
    <!-- 订单详情弹窗 -->
    <el-dialog title="订单详情" :visible.sync="dialogVisible" width="50%">
      <div v-if="currentOrder">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单编号">{{ currentOrder.orderNumber }}</el-descriptions-item>
          <el-descriptions-item label="商品总金额">¥{{ currentOrder.totalAmount }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(currentOrder.status)">
              {{ getStatusText(currentOrder.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="配送费">¥{{ currentOrder.deliveryFee || 0 }}</el-descriptions-item>
          <el-descriptions-item label="收货地址">{{ currentOrder.address }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentOrder.phone }}</el-descriptions-item>
          <el-descriptions-item label="下单时间" :span="2">{{ formatDate(currentOrder.createdTime) }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ currentOrder.remarks || '无' }}</el-descriptions-item>
        </el-descriptions>
        
        <h3>订单商品</h3>
        <el-table :data="orderItems" style="width: 100%">
          <el-table-column prop="name" label="商品名称"></el-table-column>
          <el-table-column prop="price" label="单价" width="120">
            <template slot-scope="scope">
              ¥{{ scope.row.price }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="100"></el-table-column>
          <el-table-column label="小计" width="120">
            <template slot-scope="scope">
              ¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
        
        <div v-if="currentOrder.status === 2" class="navigation-btn">
          <el-button type="warning" @click="navigateToOrder(currentOrder)">导航到配送地址</el-button>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="success" v-if="currentOrder && currentOrder.status === 1" @click="takeOrderInDialog">接单</el-button>
        <el-button type="success" v-if="currentOrder && currentOrder.status === 2" @click="completeOrderInDialog">完成配送</el-button>
      </span>
    </el-dialog>
    
    <!-- 导航信息弹窗 -->
    <el-dialog title="导航信息" :visible.sync="navigationDialogVisible" width="40%">
      <div v-loading="navigationLoading">
        <div v-if="navigateError" class="navigate-error">
          <i class="el-icon-warning"></i>
          <p>{{ navigateError }}</p>
        </div>
        <div v-else-if="locationInfo" class="location-info">
          <p><span class="label">收货地址：</span>{{ locationInfo.address }}</p>
          <p><span class="label">经度：</span>{{ locationInfo.longitude }}</p>
          <p><span class="label">纬度：</span>{{ locationInfo.latitude }}</p>
          
          <div class="navigation-options">
            <h4>选择导航方式：</h4>
            <el-button type="primary" @click="openMapNavigation('gaode')">高德地图</el-button>
            <el-button type="primary" @click="openMapNavigation('baidu')">百度地图</el-button>
            <el-button type="primary" @click="openMapNavigation('tencent')">腾讯地图</el-button>
            <el-button type="primary" @click="copyLocationToClipboard">复制坐标</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAvailableOrders, takeOrder, completeOrder, getInProgressOrders, getCompletedOrders, getOrderLocation } from '@/api/rider';
import { mapState } from 'vuex';

export default {
  name: 'RiderOrder',
  data() {
    return {
      activeTab: 'available',
      loading: false,
      orders: [],
      currentOrder: null,
      orderItems: [],
      dialogVisible: false,
      pagination: {
        page: 1,
        size: 10,
        total: 0
      },
      // 导航相关
      navigationDialogVisible: false,
      navigationLoading: false,
      locationInfo: null,
      navigateError: null
    }
  },
  computed: {
    ...mapState(['userInfo'])
  },
  created() {
    // 根据URL参数自动选择标签页
    const tabParam = this.$route.query.tab;
    if (tabParam && ['available', 'inProgress', 'completed'].includes(tabParam)) {
      this.activeTab = tabParam;
    }
    this.loadOrders();
  },
  methods: {
    // 加载订单数据
    loadOrders() {
      this.loading = true;
      
      const params = {
        page: this.pagination.page,
        size: this.pagination.size
      };
      
      let request;
      const riderId = this.userInfo.id;
      
      if (this.activeTab === 'available') {
        request = getAvailableOrders(params);
      } else if (this.activeTab === 'inProgress') {
        request = getInProgressOrders(riderId, params);
      } else if (this.activeTab === 'completed') {
        request = getCompletedOrders(riderId, params);
      }
      
      request.then(res => {
        if (res.code === 200) {
          this.orders = res.data.records || [];
          this.pagination.total = res.data.total || 0;
        } else {
          this.$message.error(res.message || '获取订单数据失败');
        }
      }).catch(err => {
        console.error('获取订单失败', err);
        this.$message.error('获取订单数据失败');
      }).finally(() => {
        this.loading = false;
      });
    },
    
    // Tab切换处理
    handleTabChange() {
      this.pagination.page = 1;
      this.loadOrders();
    },
    
    // 接单处理
    handleTakeOrder(order) {
      this.$confirm('确认接单？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doTakeOrder(order.id);
      }).catch(() => {});
    },
    
    // 执行接单
    doTakeOrder(orderId) {
      const riderId = this.userInfo.id;
      this.loading = true;
      
      takeOrder(orderId, riderId).then(res => {
        if (res.code === 200) {
          this.$message.success('接单成功');
          this.loadOrders();
          this.dialogVisible = false;
        } else {
          this.$message.error(res.message || '接单失败');
        }
      }).catch(err => {
        console.error('接单失败', err);
        this.$message.error('接单失败');
      }).finally(() => {
        this.loading = false;
      });
    },
    
    // 完成订单处理
    handleCompleteOrder(order) {
      this.$confirm('确认已完成配送？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doCompleteOrder(order.id);
      }).catch(() => {});
    },
    
    // 执行完成订单
    doCompleteOrder(orderId) {
      const riderId = this.userInfo.id;
      this.loading = true;
      
      completeOrder(orderId, riderId).then(res => {
        if (res.code === 200) {
          this.$message.success('订单已完成');
          this.loadOrders();
          this.dialogVisible = false;
        } else {
          this.$message.error(res.message || '操作失败');
        }
      }).catch(err => {
        console.error('完成订单失败', err);
        this.$message.error('操作失败');
      }).finally(() => {
        this.loading = false;
      });
    },
    
    // 查看订单详情
    viewOrder(order) {
      this.currentOrder = order;
      this.orderItems = [];
      
      // 解析商品数据
      try {
        if (order.items) {
          this.orderItems = JSON.parse(order.items);
        }
      } catch (e) {
        console.error('解析订单商品数据失败', e);
      }
      
      this.dialogVisible = true;
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待支付',
        1: '待接单',
        2: '配送中',
        3: '已完成',
        4: '已取消'
      };
      return statusMap[status] || '未知状态';
    },
    
    // 获取状态标签类型
    getStatusType(status) {
      const typeMap = {
        0: 'info',
        1: 'warning',
        2: 'primary',
        3: 'success',
        4: 'danger'
      };
      return typeMap[status] || '';
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '-';
      const date = new Date(dateStr);
      return date.toLocaleString();
    },
    
    // 分页大小变化
    handleSizeChange(size) {
      this.pagination.size = size;
      this.pagination.page = 1;
      this.loadOrders();
    },
    
    // 页码变化
    handleCurrentChange(page) {
      this.pagination.page = page;
      this.loadOrders();
    },
    
    // 在弹窗中接单
    takeOrderInDialog() {
      if (this.currentOrder) {
        this.handleTakeOrder(this.currentOrder);
      }
    },
    
    // 在弹窗中完成订单
    completeOrderInDialog() {
      if (this.currentOrder) {
        this.handleCompleteOrder(this.currentOrder);
      }
    },
    
    // 导航到订单配送地址
    navigateToOrder(order) {
      this.navigationLoading = true;
      this.navigationDialogVisible = true;
      this.locationInfo = null;
      this.navigateError = null;
      
      getOrderLocation(order.id)
        .then(res => {
          if (res.code === 200 && res.data) {
            this.locationInfo = res.data;
            if (!this.locationInfo.longitude || !this.locationInfo.latitude) {
              this.navigateError = '无法获取该地址的经纬度信息，请手动导航。';
            }
          } else {
            this.navigateError = res.message || '获取地址坐标失败';
          }
        })
        .catch(err => {
          console.error('获取地址坐标失败', err);
          this.navigateError = '获取地址坐标失败，请稍后重试';
        })
        .finally(() => {
          this.navigationLoading = false;
        });
    },
    
    // 打开地图导航
    openMapNavigation(mapType) {
      if (!this.locationInfo || !this.locationInfo.latitude || !this.locationInfo.longitude) {
        this.$message.error('无法获取地址坐标');
        return;
      }
      
      const { latitude, longitude, address } = this.locationInfo;
      let url = '';
      
      switch (mapType) {
        case 'gaode': // 高德地图
          url = `https://uri.amap.com/navigation?to=${longitude},${latitude},${encodeURIComponent(address)}&mode=ride&callnative=0`;
          break;
        case 'baidu': // 百度地图
          url = `https://api.map.baidu.com/direction?destination=latlng:${latitude},${longitude}|name:${encodeURIComponent(address)}&mode=riding&output=html`;
          break;
        case 'tencent': // 腾讯地图
          url = `https://apis.map.qq.com/uri/v1/routeplan?type=drive&to=${encodeURIComponent(address)}&tocoord=${latitude},${longitude}`;
          break;
        default:
          this.$message.error('不支持的地图类型');
          return;
      }
      
      window.open(url, '_blank');
    },
    
    // 复制坐标到剪贴板
    copyLocationToClipboard() {
      if (!this.locationInfo || !this.locationInfo.latitude || !this.locationInfo.longitude) {
        this.$message.error('无法获取地址坐标');
        return;
      }
      
      const text = `${this.locationInfo.latitude},${this.locationInfo.longitude}`;
      
      try {
        // 创建临时input元素
        const input = document.createElement('input');
        input.value = text;
        document.body.appendChild(input);
        input.select();
        document.execCommand('copy');
        document.body.removeChild(input);
        
        this.$message.success('坐标已复制到剪贴板');
      } catch (err) {
        console.error('复制失败', err);
        this.$message.error('复制失败');
      }
    }
  }
}
</script>

<style scoped>
.order-container {
  padding: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.empty-data {
  margin-top: 40px;
  text-align: center;
}

.navigation-btn {
  margin-top: 20px;
  text-align: center;
}

.navigate-error {
  text-align: center;
  color: #f56c6c;
  padding: 20px;
}

.navigate-error i {
  font-size: 40px;
  margin-bottom: 10px;
}

.location-info {
  padding: 15px;
}

.location-info .label {
  font-weight: bold;
  display: inline-block;
  width: 80px;
}

.navigation-options {
  margin-top: 20px;
  border-top: 1px solid #eee;
  padding-top: 15px;
}

.navigation-options h4 {
  margin-bottom: 15px;
}

.navigation-options .el-button {
  margin: 0 10px 10px 0;
}
</style> 